'use strict';
/**
 * Created by FreezeSoul on 2015/10/18.
 */
define([
        'angular',
        'app/modules/dataset/define',
        'app/modules/dataset/services/dataset',
        'app/modules/dataset/controllers/dataset-param',
        'app/modules/source/services/source'
    ],
    function (angular) {
        angular.module('ad.dataset')
            .controller('adDataSetDataBaseController', ['$scope', '$stateParams', '$uibModal', '_', 'Notification', 'adDataSetService', 'adSourceService'
                , function ($scope, $stateParams, $uibModal, _, Notification, dataSetService, dataSouceService) {
                    //Parent Object: $scope.dataSet.DataSet.DataServiceMeta
                    $scope.dataSources = [];

                    $scope.dataColumns = [];

                    $scope.executeData = [];

                    $scope.tables = [];

                    $scope.columns = [];

                    if (!$scope.dataset_defines.DataServiceMeta.DataSouceLink) {
                        $scope.dataset_defines.DataServiceMeta.DataSouceLink = 0;
                    }
                    if (!$scope.dataset_defines.DataServiceMeta.QuerySqlString) {
                        $scope.dataset_defines.DataServiceMeta.QuerySqlString = '';
                    }
                    if (!$scope.dataset_defines.DataServiceMeta.QuerySqlParams) {
                        $scope.dataset_defines.DataServiceMeta.QuerySqlParams = [];
                    }


                    if ($scope.$stateParams.datasetid == 0) {
                        $scope.dataset_defines.DataServiceMeta.DataSouceLink = 0;
                        $scope.dataset_defines.DataServiceMeta.QuerySqlString = '';
                        $scope.dataset_defines.DataServiceMeta.QuerySqlParams = [];
                    } else {
                        if (angular.isArray($scope.dataset_defines.DataColumnsMap)) {
                            _.each($scope.dataset_defines.DataColumnsMap, function (map) {
                                if (map.Column && $scope.dataColumns.indexOf(map.Column) == -1) {
                                    $scope.dataColumns.push(map.Column);
                                }
                            });
                        }
                    }


                    $scope.aceLoaded = function (_editor) {
                        $scope.sqlEditor = _editor;
                        $scope.aceSession = _editor.getSession();

                        _editor.session.setMode("ace/mode/sql");
                        _editor.setTheme("ace/theme/dreamweaver");
                        _editor.$blockScrolling = Infinity;

                        _editor.setOptions({
                            enableBasicAutocompletion: true,
                            enableLiveAutocompletion: true,
                            enableSnippets: false,
                            fontSize: 16,
                            wrap: true
                        });

                        $scope.$on('$destroy', function () {
                            _editor.destroy();
                            _editor.container.remove();
                        });

                        _editor.on("blur", function () {
                            var sql = _editor.getSession().getDocument().getValue();
                            sql = dataSetService.filterSqlString(sql);
                            _editor.setValue(sql);
                        });

                        if ($scope.dataset_defines.DataServiceMeta.QuerySqlString !== undefined)
                            _editor.setValue($scope.dataset_defines.DataServiceMeta.QuerySqlString);
                    };

                    $scope.aceChanged = function () {
                        $scope.dataset_defines.DataServiceMeta.QuerySqlString = $scope.aceSession.getDocument().getValue();
                    };

                    $scope.getDataSource = function () {
                        dataSouceService.getAll().then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.dataSources = obj.data;
                                $scope.changeSourceLink($scope.dataset_defines.DataServiceMeta.DataSouceLink);
                            } else {
                                Notification.error('数据源加载失败！');
                            }
                        });
                    };

                    $scope.changeSourceLink = function (selectedLink) {
                        if (!selectedLink) return;
                        var source = _.find($scope.dataSources, function (source) {
                            return source.datasource_id == selectedLink;
                        });
                        dataSouceService.getMeta(source).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                if (obj.data.tables && obj.data.columns) {
                                    $scope.tables = obj.data.tables;
                                    $scope.columns = obj.data.columns;
                                    bindAutoCompletion();
                                    Notification.success('数据表、列自动提示加载成功！');
                                }
                            }
                        });
                    };

                    var bindAutoCompletion = function () {
                        var langTools = ace.require('ace/ext/language_tools');
                        var rhymeCompleter = {
                            getCompletions: function (editor, session, pos, prefix, callback) {
                                if (prefix.length === 0) {
                                    callback(null, []);
                                    return
                                }
                                var table_list = _.map($scope.tables, function (table) {
                                    return {name: table[0], value: table[0], meta: "Tables"}
                                });
                                var column_list = _.map($scope.columns, function (column) {
                                    return {name: column[0] + '(' + column[1] + ')', value: column[0], meta: "Columns"}
                                });
                                callback(null, table_list.concat(column_list));
                            }
                        };
                        langTools.setCompleters([langTools.snippetCompleter, langTools.textCompleter, langTools.keyWordCompleter, rhymeCompleter]);
                    };

                    $scope.executeSql = function () {
                        var sql = $scope.dataset_defines.DataServiceMeta.QuerySqlString;
                        if (!sql) return;
                        $scope.sqlEditor.setValue(sql);
                        var params = $scope.dataset_defines.DataServiceMeta.QuerySqlParams;
                        var link = $scope.dataset_defines.DataServiceMeta.DataSouceLink;
                        if (link == 0) return;
                        var source = _.find($scope.dataSources, function (source) {
                            return source.datasource_id == link;
                        });
                        dataSouceService.executeSql(source, sql, params).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.executeData = obj.data.data;
                                $scope.dataColumns = obj.data.columns;
                                Notification.success('数据加载成功！');
                            } else {
                                Notification.error('数据加载失败，请检查数据源和执行SQL！');
                            }
                        });
                    };

                    $scope.paramsSet = function () {
                        var paramsList = dataSetService.patternParams($scope.dataset_defines.DataServiceMeta.QuerySqlString);
                        if (paramsList.length > 0 && $scope.dataset_defines.DataServiceMeta.QuerySqlParams.length === 0) {
                            $scope.dataset_defines.DataServiceMeta.QuerySqlParams = _.map(paramsList, function (p) {
                                return {
                                    ParamName: p,
                                    DataType: '',
                                    DefaultValue: ''
                                }
                            });
                        }

                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/dataset/views/dataset-param.tpl.html',
                            controller: 'adDateSetParamController',
                            size: 'lg',
                            resolve: {
                                items: function () {
                                    return $scope.dataset_defines.DataServiceMeta.QuerySqlParams;
                                }
                            }
                        });

                        modalInstance.result.then(function (items) {
                            _.each(items, function (item) {
                                if (item.DefaultValue === undefined) {
                                    item.DefaultValue = "";
                                }
                            });
                            $scope.dataset_defines.DataServiceMeta.QuerySqlParams = items;
                        }, function () {
                        });
                    };

                    $scope.getDataSource();
                }]);
    });